<?php
header('Content-Type: text/html; charset=utf-8');
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
require_once dirname(__FILE__) . '/../../../libs/phpMailer/class.phpmailer.php';
session_name(SESSION);
session_start();
$myPdo = DbUtils::createPdoInst();
$action = MiscUtils::getParam('action', '');
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'remove':
      remove($myPdo);
      break;
    case 'emptycart':
      emptycart($myPdo);
      break;
    case 'savenow':
      savenow($myPdo);
      break;
    case 'checkout':
      checkout($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo $e->getMessage();
}

function remove($myPdo) {
  $idx = MiscUtils::getParam('idx', '');
  $to = MiscUtils::getParam('to', '');
  
  if (!isset($_SESSION['my_cart'])) {
    $_SESSION['my_cart'] = array();
  }
  
  if (isset($_SESSION['my_cart'][$idx])) {
    array_splice($_SESSION['my_cart'], $idx, 1);
    setcookie('my_cart', json_encode($_SESSION['my_cart']), time() + 86400 * 7);
  }
  
  echo "
  <script>
  location.href = '$to';
  </script>
  ";
  return;
}

function emptycart($myPdo) {
  $to = MiscUtils::getParam('to', '');
  
  unset($_SESSION['my_cart']);
  setcookie('my_cart', json_encode(array()), time() - 3600);
  
  echo "
  <script>
  location.href = '$to';
  </script>
  ";
  return;
}

function savenow($myPdo) {
  $last_cart = json_decode(MiscUtils::getParam('last_cart', ''));
  $to = MiscUtils::getParam('to', '');
  
  $_SESSION['my_cart'] = $last_cart;
  setcookie('my_cart', json_encode($_SESSION['my_cart']), time() + 86400 * 7);
  
  foreach ($_SESSION['my_cart'] as $idx => $pur) {
    unset($_SESSION['stock_err' . $idx]);
    if ($pur->_stock < $pur->quantity) {
      $_SESSION['stock_err' . $idx] = 'Out of stock';
    }
  }
  
  echo "
  <script>
  location.href = '$to';
  </script>
  ";
  return;
}

function checkout($myPdo) {
  $last_cart = json_decode(MiscUtils::getParam('last_cart', ''));
  $from = MiscUtils::getParam('from', '');
  $to = MiscUtils::getParam('to', '');
  
  $_SESSION['my_cart'] = $last_cart;
  setcookie('my_cart', json_encode($_SESSION['my_cart']), time() + 86400 * 7);
  
  $is_error = 0;
  foreach ($_SESSION['my_cart'] as $idx => $pur) {
    if ($pur->_stock < $pur->quantity && $pur->_enabled_stock == 1) {
      $is_error = 1;
    }
  }
  
  if ($is_error == 1) {
    echo "
    <script>
    location.href = '$from';
    </script>
    ";
    return;
  }
  
  echo "
  <script>
  parent.location.href = '$to';
  </script>
  ";
  return;
}
?>
